<template>
    <div class="account_container">
        <!-- 我的账户:个人账户 -->
        <div class="account">
            <div class="amount_card">
                <div class="amount_card_info">
                    <div>可用余额：</div>
                    <div class="price">{{ state.balance || '-' }}</div>
                </div>
                <div class="amount_card_btn">
                    <el-button type="primary" @click="onWithdrawals">提现</el-button>
                </div>
            </div>

            <div class="income_part">
                <div class="income_bill">
                    <div>待结算的分账收入：</div>
                    <div class="num">{{ state.waitSubAccountIncome || '-' }}</div>
                </div>
            </div>

            <div class="title">
                账户收支明细
                <span>资金流水明细是账户流水明细，未结算订单不会产生资金出入账。</span>
            </div>

            <!-- 查询 -->
            <div class="search">
                <el-form ref="paramsRef" :model="params" label-width="80">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="动向" prop="flowDirection">
                                <el-select v-model="params.flowDirection" placeholder="全部">
                                    <el-option
                                        v-for="item in options"
                                        :label="item.label"
                                        :value="item.value"
                                        :key="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="变动类型" prop="changeType">
                                <el-select v-model="params.changeType" placeholder="全部">
                                    <el-option
                                        v-for="item in typeOptions"
                                        :label="item.label"
                                        :value="item.value"
                                        :key="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="订单编号" prop="objectSn">
                                <el-input v-model="params.objectSn" placeholder="输入订单编号"> </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="来源" label-width="40" prop="source">
                                <el-input v-model="params.source" placeholder="输入企业名称、用户姓名、登录号">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="变动时间" prop="createdAt">
                                <el-date-picker
                                    v-model="params.createdAt"
                                    type="daterange"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    :default-time="defaultDateRange"
                                    range-separator="-"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label-width="0">
                                <el-button type="primary" @click="onSearch">查询</el-button>
                                <el-button plain @click="onReset">清空</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" class="zw-form-btns">
                            <el-button plain @click="onExport">导出</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 列表 -->
            <div class="table_card">
                <el-table :data="state.list" stripe>
                    <el-table-column prop="flowDirectionName" width="60" label="动向"></el-table-column>
                    <el-table-column prop="changeTypeName" min-width="100" label="变动类型"></el-table-column>
                    <el-table-column prop="" min-width="120" label="订单编号">
                        <template v-slot="{ row }">
                            <span v-if="row.changeType == 1 || row.changeType == 5">{{ row.objectSn || '-' }}</span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="changeAmount" min-width="80" label="金额">
                        <template v-slot="{ row }">
                            <!-- 按入账和出账区分 -->
                            <span v-if="row.flowDirection === 'income'">+</span
                            ><span v-if="row.flowDirection === 'expenditure'">-</span>
                            <span>￥{{ priceFilter(floatDivide(Math.abs(row.changeAmount), 100) || 0) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdAt" width="180" label="变动时间"></el-table-column>
                    <el-table-column prop="remark" min-width="110" label="备注">
                        <template v-slot="{ row }">
                            <div v-if="row.changeType == 1 || row.changeType == 5">-</div>
                            <div v-else>
                                <!--区分 \r 换行 -->
                                <div v-for="(item, index) in (row.remark || '-').split('\\r')" :key="index">
                                    {{ item }}
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="source" min-width="110" label="来源信息">
                        <template v-slot="{ row }">
                            <template v-if="[2, 3, 6].includes(row.changeType)">-</template>
                            <template v-else>
                                <div>{{ sourceNamelabel(row) }}：{{ row.sourceName }}</div>
                                <div>登录号：{{ row.sourceLoginNo }}</div>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination_card">
                <Pagination
                    :pageSize="params.perPage"
                    :currentPage="params.page"
                    :total="state.total"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>

        <!-- 提现弹框 -->
        <div class="withdrawals_dialog">
            <el-dialog v-model="state.show" title="申请提现" width="400px" @closed="onClosed">
                <div class="content">
                    <el-form ref="formRef" :model="form" label-width="auto" @submit.prevent>
                        <el-form-item label="可用余额">{{ state.balance }}</el-form-item>
                        <el-form-item label="提现至">{{ state.bankCardNumber }}</el-form-item>
                        <el-form-item label="提现金额" prop="amount" :rules="rules.amount">
                            <el-input-number
                                class="input_width_200"
                                v-model="form.amount"
                                :min="0.01"
                                :max="+state.money"
                                :precision="2"
                                :controls="false"
                                placeholder="请输入大于0的数字" />
                            <span class="margin_left_2px"> 元</span>
                        </el-form-item>
                        <el-form-item label="  ">
                            <div class="desc">预计1个工作日到账</div>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="onCofirm(formRef)">立即提现</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import Pagination from '@/components/Pagination.vue';
import request from '@/request';
import { floatMultiply, floatDivide, downLoadUrl, dealObjectEmptyValue } from '@/commons/utils';
import store from '@/store';
import storage from '@/commons/storage';
import { reactive, ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const Address = '?Address=' + location.origin + location.pathname;

const props = defineProps({
    baseInfoObj: { type: Object, default: () => {} },
    loginNo: { type: String, default: '' }
});
const options = [
    { label: '全部', value: '' },
    { label: '入账', value: 'income' },
    { label: '出账', value: 'expenditure' }
];
const typeOptions = [
    { label: '全部', value: 0 },
    { label: '分账收入', value: 5 },
    { label: '提现', value: 6 },
    { label: '提现_企业打款', value: 7 }
];

const defaultDateRange = [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)];

const params = reactive({
    perPage: 10,
    page: 1,
    flowDirection: '',
    changeType: 0,
    objectSn: '',
    source: '',
    createdAt: []
});
const state = reactive({
    show: false,
    // 待结算的分账收入（string）
    waitSubAccountIncome: '',
    list: [],
    total: 0,
    balance: '' // 可用余额文案
});

// 来源信息名称
const sourceNamelabel = row => {
    let name = '名称';
    if (row.changeType == 1 || row.changeType == 5) {
        name = '企业名称';
    } else if (row.changeType == 4) {
        name = '姓名';
    }
    return name;
};

// 提现弹窗
const formRef = ref(null);
const amountValidator = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入提现金额'));
    } else if (value < 0.01) {
        callback(new Error('提现金额不能小于0.01元'));
    } else if (value > state.money) {
        callback(new Error('提现金额不能大于可用余额'));
    } else {
        callback();
    }
};
const rules = {
    amount: [
        { required: true, message: '请输入提现金额', trigger: 'blur' },
        { validator: amountValidator, trigger: 'blur' }
    ]
};
const form = reactive({
    amount: null,
    loginNo: props.loginNo
});
// 打开提现弹框
const onWithdrawals = async () => {
    if (+state.money === 0) {
        ElMessage.error('可用余额为0，不可申请提现');
        return;
    }
    const { data } = await request('checkPasswordSetServ', { loginNo: props.loginNo });
    // 设置了支付密码为空，没设置有url
    if (data?.url) {
        ElMessageBox.alert('请先设置提现密码', '提示', {
            confirmButtonText: '立即设置',
            callback: action => {
                if (action == 'confirm') {
                    storage.set('ZW-LOGIN_NO', props.loginNo);
                    window.open(data?.url + Address, '_blank');
                }
            }
        });
    } else {
        state.show = true;
    }
};
// 关闭提现弹框
const onClosed = () => {
    formRef.value.resetFields();
    form.amount = null;
};

// 提现确认
const onCofirm = async formEl => {
    if (!formEl) return;
    await formEl.validate(async valid => {
        if (valid) {
            let result = {};
            Object.assign(result, form);
            result.amount = floatMultiply(result.amount, 100).toString();
            const { data } = await request('baofuWithdraw', result);
            if (data.url) {
                const url = data.url + Address;
                storage.set('ZW-LOGIN_NO', props.loginNo);
                window.open(url, '_self');
            }
        }
    });
};

// 账户余额查询
const getData = async () => {
    const res = await request('baofuBalance', { loginNo: props.loginNo });
    state.balance = `￥${floatDivide(res.data.money, 100).toFixed(2)}`;
    const { bankName, cardNoStar } = props.baseInfoObj;
    state.bankCardNumber = `${bankName}  (${cardNoStar})`;
    state.money = floatDivide(res.data.money, 100).toFixed(2);
};

// 账户收支明细-列表
const getList = async () => {
    const { data } = await request(
        'queryCapitalListServ',
        dealObjectEmptyValue(Object.assign(params, { loginNo: props.loginNo }))
    );
    state.list = data.data || [];
    state.total = data.total || 0;
};

// 查询
const onSearch = () => {
    params.page = 1;
    getList();
};
// 清空
const paramsRef = ref();
const onReset = () => {
    paramsRef.value.resetFields();
    params.page = 1;
    getList();
};
// 页码条数变更
const changeSizeHandler = v => {
    params.page = 1;
    params.perPage = v;
    getList();
};

// 页码变更
const changePageHandler = v => {
    params.page = v;
    getList();
};

// 导出
const onExport = () => {
    request('capitalExportServ', dealObjectEmptyValue(Object.assign(params, { loginNo: props.loginNo }))).then(res => {
        if (res?.data?.url) {
            downLoadUrl(res.data.url);
        }
    });
};

// 获取分账收入金额
const queryAmount = async () => {
    const { data } = await request('queryCapitalAmountServ', { loginNo: props.loginNo });
    state.waitSubAccountIncome = `￥${floatDivide(data?.waitSubAccountIncome || 0, 100).toFixed(2)}`;
};

onMounted(() => {
    getData();
    getList();
    queryAmount();
});
</script>

<style lang="scss" src="./account.scss" scoped></style>
